#coding:utf-8

import xlrd.sheet,xlrd.book,xlrd
import xlwt
from xlutils.copy import copy
import unittest


NAME_LIST = ('ActualResult','TestResult','RunningTime') #需要被记录cell坐标的名称

class Handle:

    def __init__(self,name):
        self.name = name
        self.path = '../testCase/'+self.name

    def open_Work(self):
        try:
            work = xlrd.open_workbook(self.path,formatting_info=False)
            return  work.sheets()
        except Exception as e:
            print('打开excel失败',e)

    '''读取excel表格'''
    def readSheet(self,sheet:xlrd.sheet.Sheet):
        sheet_dict = {}
        testCase = []
        if isinstance(sheet,xlrd.sheet.Sheet):
            nrows = sheet.nrows
            ncols = sheet.ncols
            sheet_dict['Interface'] = sheet.cell_value(0,1)
            sheet_dict['Method'] = sheet.cell_value(2,1)
            sheet_dict['Args'] = sheet.cell_value(3,1).split('|')
            sheet_dict['sheet_name'] = sheet.name
            for row in range(5,nrows):
                case = {}
                if sheet.cell_value(row,0) == '':
                    continue
                for col in range(ncols):
                    cell_name = sheet.cell_value(4,col)
                    if cell_name in NAME_LIST:
                        case[cell_name] = {'row':row,'col':col}
                    elif sheet.cell_type(row,col) == 2:
                        case[cell_name] = int(sheet.cell_value(row,col))
                    else:
                        case[cell_name] = sheet.cell_value(row,col)
                testCase.append(case)
            sheet_dict['TestCase'] = testCase
        else:
            print('sheet格式错误')
        return sheet_dict

    def readSheets(self):
        sheets = self.open_Work()
        return sheets

    '''获取写excel workbook'''
    def getWorkbook(self):
        wb = xlrd.open_workbook(self.path,formatting_info=True)
        self.workbook = copy(wb) # type:xlwt.Workbook
        return self.workbook

    '''写入单元格'''
    def writeCell(self,row,col,value,sheet):
        if value == 'pass':
            style = self.setStyle(50)
            sheet.write(row,col,value,style)
        elif value == 'fail':
            style = self.setStyle(2)
            sheet.write(row,col,value,style)
        else:
            sheet.write(row,col,value)

    def saveWorkbook(self):
        self.workbook.save('../logs/'+self.name)

    '''设置单元格背景颜色'''
    def setStyle(self,color):
        pattern = xlwt.Pattern()
        pattern.pattern = xlwt.Pattern.SOLID_PATTERN
        pattern.pattern_fore_colour = color
        pattern.pattern_back_colour = 35
        style = xlwt.XFStyle()
        style.pattern = pattern
        return style



if __name__ == '__main__':
    ex = Handle('F:\\interfaceTest\\testCase\\门店防盗.xls')
    # ex.readSheets()
    ex.writeSheet()




